{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "用Python编写适应度函数get_adjust"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_adjust(std_error, y, indiv_data, handle):\n",
    "    \"\"\"计算适应度，通过外部定义的handle来处理，同时适用于分类和回归问题\"\"\"\n",
    "    X = indiv_data\n",
    "    cur_error = handle(X,y)\n",
    "    return std_error - cur_error if std_error > cur_error else 0"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "两类handle处理函数，一类用于分类，一类用于回归"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn import tree\n",
    "from sklearn import linear_model \n",
    "\n",
    "def evaluation_classify(X,y):\n",
    "    \"\"\"建立分类问题的评估方法\"\"\"\n",
    "    clf = tree.DecisionTreeClassifier(random_state=0)\n",
    "    errors = []\n",
    "    for i in range(X.shape[0]):\n",
    "        index = [e for e in range(X.shape[0])]\n",
    "        index.remove(i)\n",
    "        X_train = X.iloc[index,:]\n",
    "        X_test = X.iloc[[i],:]\n",
    "        y_train = y[index]\n",
    "        y_test = y[i]\n",
    "        clf.fit(X_train, y_train)\n",
    "        errors.extend(clf.predict(X_test) != y_test)\n",
    "    return np.sum(errors)/len(errors)\n",
    "\n",
    "def evaluation_regression(X,y):\n",
    "    \"\"\"建立回归问题的评估方法\"\"\"\n",
    "    reg = linear_model.LinearRegression()\n",
    "    errors = 0\n",
    "    for i in range(X.shape[0]):\n",
    "        index = [e for e in range(X.shape[0])]\n",
    "        index.remove(i)\n",
    "        X_train = X.iloc[index,:]\n",
    "        X_test = X.iloc[[i],:]\n",
    "        y_train = y[index]\n",
    "        y_test = y[i]\n",
    "        reg.fit(X_train, y_train)\n",
    "        errors = errors + (y_test - reg.predict(X_test)[0])**2\n",
    "    return errors/np.sum(y)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
